package com.gmcloud.plugin.captcha.utils;

import com.gmcloud.plugin.captcha.vo.PointVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @author zl.sir
 * @version 1.0
 * @since 2022/8/30 22:52
 *  替换掉fastjson，自定义实现相关方法
 *  note: 该实现不具有通用性，仅用于本项目。
 */
public class JsonUtil {

    private JsonUtil(){
        throw new IllegalArgumentException("static class");
    }
    private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class);
    public static List<PointVO> parseArray(String text, Class<PointVO> clazz) {
        if (text == null) {
            return Collections.emptyList();
        } else {
            String[] arr = text.replaceFirst("\\[","")
                    .replaceFirst("]","").split("}");
            List<PointVO> ret = new ArrayList<>(arr.length);
            for (String s : arr) {
                ret.add(parseObject(s,PointVO.class));
            }
            return ret;
        }
    }


    public static PointVO parseObject(String text, Class<PointVO> clazz) {
        if(text == null) {
            return null;
        }
        /*if(!clazz.isAssignableFrom(PointVO.class)) {
			throw new UnsupportedOperationException("不支持的输入类型:"
					+ clazz.getSimpleName());
		}*/
        try {
            PointVO ret = clazz.getDeclaredConstructor().newInstance();
            return ret.parse(text);
        }catch (Exception ex){
            logger.error("json解析异常", ex);

        }
        return null;
    }

    public static String toJSONString(Object object) {
        if(object == null) {
            return "{}";
        }
        if(object instanceof PointVO t){
            return t.toJsonString();
        }
        if(object instanceof List l){
            StringBuilder buf = new StringBuilder("[");
            ((List<PointVO>) l).forEach(t-> buf.append(t.toJsonString()).append(","));
            return buf.deleteCharAt(buf.lastIndexOf(",")).append("]").toString();
        }
        if(object instanceof Map map){
            return map.entrySet().toString();
        }
        throw new UnsupportedOperationException("不支持的输入类型:"
                +object.getClass().getSimpleName());
    }
}
